package com.lhk.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class JDBCController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    //查询employee表中所有数据
    //List 中的1个 Map 对应数据库的 1行数据
    //Map 中的 key 对应数据库的字段名，value 对应数据库的字段值
    @GetMapping("/userList")
    public List<Map<String, Object>> userList(){
        String sql = "select * from mybatis.user";
        List<Map<String, Object>> userList = jdbcTemplate.queryForList(sql);
        return userList;
    }

    @GetMapping("/add")
    public String addUser(){
        String sql = "insert into mybatis.user(id,name,pwd) value (6,'xaisohen','123456')";
        int update = jdbcTemplate.update(sql);
        return update + " addok";
    }

    @GetMapping("/update/{id}")
    public String updateUser(@PathVariable("id") int id){
        String sql = "update mybatis.user set name=?,pwd=? where id="+id;
        /*需要修改的数据*/
        Object[] obj = new Object[2];
        obj[0] = "哈哈";
        obj[1] ="测试密码";
        int update = jdbcTemplate.update(sql,obj);
        return update + " updateok";
    }

    @GetMapping("/delUser/{id}")
    public String delUser(@PathVariable("id") int id){
        String sql = "delete from mybatis.user where id=?";
        /*需要修改的数据*/
        int update = jdbcTemplate.update(sql,id);
        return update + " updateok";
    }

}
